package com.aidex.biz.controller;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.enums.CustomerEnum;
import com.aidex.biz.domain.enums.DongTaiTypeEnum;
import com.aidex.biz.domain.enums.MessageTypeEnum;
import com.aidex.biz.domain.vo.CustomerExpertVo;
import com.aidex.biz.domain.vo.GuanggaoChengBen;
import com.aidex.biz.domain.vo.YuanGongGongziVo;
import com.aidex.biz.service.*;
import com.aidex.biz.utils.AliQwenUtils;
import com.aidex.biz.utils.RongXiangKeAESUtil;
import com.aidex.biz.utils.YunXiangYouKeAESUtils;
import com.aidex.common.annotation.Log;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.AjaxResult;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.domain.model.LoginUser;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.http.HttpUtils;
import com.aidex.common.utils.poi.ExcelUtil;
import com.aidex.common.utils.sign.Md5Utils;
import com.aidex.framework.websocket.WebSocketServer;
import com.aidex.framework.websocket.WebSocketUsers;
import com.aidex.system.service.ISysUserService;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.bouncycastle.pqc.math.linearalgebra.IntUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 左心房客户推送信息Controller
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-04-03
 */
@RestController
@RequestMapping("/biz/bizCustomer")
public class CustomerController extends BaseController {
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private CustomerDongtaiService customerDongtaiService;

    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private CustomerXiezuService customerXiezuService;

    @Autowired
    private BusinessSetService businessSetService;
    @Autowired
    private MessageInfoService messageInfoService;

    @Autowired
    private XiansuoChengbenLogService xiansuoChengbenLogService;
    @Autowired
    private CustomerReceiveService customerReceiveService;
    @Autowired
    private PushCustomerService pushCustomerService;

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date setTime = sdf.parse("08:08:23");
        Date endTime = sdf.parse("20:18:23");
        LocalTime now = LocalTime.now();
        // 定义时间段
        LocalTime startTime1 = LocalTime.of(setTime.getHours(), setTime.getMinutes(), setTime.getSeconds()); // 上午9点
        LocalTime endTime1 = LocalTime.of(endTime.getHours(), endTime.getMinutes(), endTime.getSeconds()); // 下午5点


        if (now.isAfter(startTime1) && now.isBefore(endTime1)) {
            System.out.println("yes");
        } else {
            System.out.println("no");
        }
    }

    /**
     * 查询左心房客户推送信息列表
     */
//    @PreAuthorize("@ss.hasPermi('biz:bizCustomer:list')")
    @GetMapping("/list")
    public R<PageInfo> list(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.findPage(customer));
    }

    @GetMapping("/yslist")
    public R<PageInfo> yslist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.ysfindPage(customer));
    }

    @GetMapping("/alllist")
    public R<PageInfo> alllist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }

        PageInfo<Customer> customerPageInfo = customerService.findAllList(customer);
        return R.data(customerPageInfo);
    }

    @GetMapping("/findZhuangKuList")
    public R<PageInfo> findZhuangKuList(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setUserId(SecurityUtils.getUserId());
        }
        PageInfo<Customer> customerPageInfo = customerService.findZhuangKuList(customer);
        return R.data(customerPageInfo);
    }


    @GetMapping("/customerWithJoinList")
    public R<PageInfo> customerWithJoinList(Customer customer, HttpServletRequest request,
            HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.findCustomerWithJoinList(customer));
    }

    @GetMapping("/daigenjinlist")
    public R<PageInfo> daigenjinlist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));

        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId()) || customer.getIsTeam() == 0) {
            customer.setUserId(SecurityUtils.getUserId());
        }
        return R.data(customerService.findDaigenjinList(customer));
    }

    @GetMapping("/xiansuochilist")
    public R<PageInfo> xiansuochilist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setUserId(SecurityUtils.getUserId());
        }

        return R.data(customerService.findPage(customer));
    }

    @GetMapping("/teamxiansuochilist")
    public R<PageInfo> teamxiansuochilist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.findPage(customer));
    }

    @GetMapping("/mylist")
    public R<PageInfo> mylist(Customer customer, HttpServletRequest request, HttpServletResponse response) {

        customer.setPage(new PageDomain(request, response));

        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setUserId(SecurityUtils.getUserId());
        }

        return R.data(customerService.findMyList(customer));
    }

    @GetMapping("/chenjiaolist")
    public R<PageInfo> chenjiaolist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.findChengJiaoList(customer));
    }

    @GetMapping("/gonghailist")
    public R<PageInfo> gonghailist(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        customer.setPage(new PageDomain(request, response));
        if (StringUtils.isEmpty(customer.getCompanyId())) {
            customer.setCompanyId(null);
        }
        return R.data(customerService.findgonghaiList(customer));
    }

    @GetMapping("/xieZuList")
    public R<PageInfo> xieZuList(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setUserId(SecurityUtils.getUserId());
        }
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.findListXieZu(customer));
    }

    /**
     * 获取左心房客户推送信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('biz:bizCustomer:query')")
    @GetMapping(value = "/{id}")
    public R<Customer> detail(@PathVariable("id") String id) {
        return R.data(customerService.get(id));
    }

    /**
     * 单个分配
     *
     * @param customer
     * @return
     */
    @GetMapping(value = "/manualShare")
    public R manualShare(Customer customer) {
        Customer customerOne = customerService.get(customer.getId());
        SysUser sysUser = iSysUserService.get(customer.getUserId());
        if (null == customerOne || null == sysUser) {
            return R.fail("业务对象为空！");
        }
        customerOne.setUserId(sysUser.getUserId());
        customerOne.setUserName(sysUser.getName());
        customerOne.setDeptId(sysUser.getDeptId());
        customerOne.setDeptName(sysUser.getDeptName());
        // 分配时间
        customerOne.setLastTime(new Date());
        // 更新状态时间
        customerOne.setOperateTime(new Date());
        if (null != customer.getStatus()) {
            customerOne.setStatus(customer.getStatus());// 转给他人到线索池或者我的客户
        }
        customerOne.setOwnType("3");// 姓名前显示【转】
        if (customerService.save(customerOne)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "fenpeiNewCus");
            jsonObject.put("msg", SecurityUtils.getLoginUser().getUser().getName() + "-分配新客户给您了");
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, sysUser.getUserId(),
                    jsonObject.toJSONString());
            messageInfoService.sendMsg(customerOne, MessageTypeEnum.JRXKH, jsonObject.getString("msg"));
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType(DongTaiTypeEnum.OPERATE.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-手动转给-" + sysUser.getName());
            customerDongtaiService.save(customerDongtai);
            //2025-5-6 彭帅提议 转给他人的不转移成本
            //xiansuoChengbenLogService.updateUserInfo(customerOne, sysUser);
            return R.success();
        }
        return R.fail("分配失败");
    }

    /**
     * 批量分配
     *
     * @param customer
     * @return
     */
    @GetMapping(value = "/manualShareBatch")
    public R manualShareBatch(Customer customer) {
        try {
            SysUser sysUser = iSysUserService.getUserCache(customer.getUserId());

            Customer customerOne = new Customer();
            customerOne.setIds(customer.getIds());
            customerOne.setStatus(customer.getStatus());
            customer.setLastTime(new Date());
            // 更新状态时间
            customer.setOperateTime(new Date());
            customer.setOwnType("3");// 姓名前显示【转】
            customer.preUpdate();
            int result = customerService.batchShareCustomersToUserByIds(customer, sysUser);
            if (result > 0) {
                CustomerDongtai customerDongtai = new CustomerDongtai();
                customerDongtai.setType(DongTaiTypeEnum.OPERATE.getStatus());
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-手动转给-" + sysUser.getName());
                customerDongtai.preInsert();
                int dtResult = customerDongtaiService.insertBatchByCustomerIds(customer.getIds(), customerDongtai);

                // 信息只发一次
                Customer customerOneSend = new Customer();
                customerOneSend.setUserId(sysUser.getUserId());
                customerOneSend.setUserName(sysUser.getName());
                customerOneSend.setDeptId(sysUser.getDeptId());
                customerOneSend.setDeptName(sysUser.getDeptName());
                //customerOneSend.setId(String.join(";", customer.getIds())); 可能有100多客户，数据量太大

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "fenpeiNewCus");
                jsonObject.put("msg", SecurityUtils.getLoginUser().getUser().getName() + "-分配新客户给您了");
                WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, sysUser.getUserId(),
                        jsonObject.toJSONString());
                messageInfoService.sendMsg(customerOneSend, MessageTypeEnum.JRXKH, jsonObject.getString("msg"));
            }
            return R.success();
        } catch (Exception exception) {
            return R.fail("分配失败:" + exception.getLocalizedMessage());
        }
    }

    /**
     * 收到分配
     *
     * @param customer
     * @return
     */
    @GetMapping(value = "/myShareCustomer")
    public R myShareCustomer(Customer customer) {
        Customer customerOne = customerService.get(customer.getId());
        SysUser sysUser = iSysUserService.get(customer.getUserId());
        if (null == customerOne || null == sysUser) {
            return R.fail("业务对象为空！");
        }
        customerOne.setUserId(sysUser.getUserId());
        customerOne.setUserName(sysUser.getName());
        customerOne.setDeptId(sysUser.getDeptId());
        customerOne.setDeptName(sysUser.getDeptName());
        customerOne.setLastTime(new Date());
        // 更新状态时间
        customerOne.setOperateTime(new Date());
        if (customerService.save(customerOne)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "fenpeiNewCus");
            jsonObject.put("msg", SecurityUtils.getLoginUser().getUser().getName() + "-分配新客户给您了");
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, sysUser.getUserId(),
                    jsonObject.toJSONString());
            messageInfoService.sendMsg(customerOne, MessageTypeEnum.JRXKH, jsonObject.getString("msg"));
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType(DongTaiTypeEnum.OPERATE.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-手动转给-" + sysUser.getName());
            customerDongtaiService.save(customerDongtai);

            return R.success();
        }
        return R.fail("分配失败");
    }

    /**
     * 新增客户信息
     */
//    @PreAuthorize("@ss.hasPermi('biz:bizCustomer:add')")
    @Log(title = "新增客户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated Customer customer) {
        if (StringUtils.isEmpty(customer.getPhone())) {
            return R.fail("客户手机号不能是空");
        }
        if (StringUtils.isEmpty(customer.getLaiyuan()) || StringUtils.isNull(customer.getLaiyuan())) {
            return R.fail("客户来源不能是空");
        }
        String pushId = UUID.randomUUID().toString();
        Date date = new Date();
        Customer customer1 = customerService.findCustomerByphone(customer.getPhone().trim());
        if (null != customer1) {
            // 更新已存在的客户 信息

            Integer isRep = 1;
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            // 没有归属的，直接归属给当前录单人员。有归属的提示重复记录在动态里，不做归属动作
            if (StringUtils.isNull(customer1.getUserId())) {
                customer1.setUserId(sysUser.getUserId());
                customer1.setUserName(sysUser.getName());
                customer1.setDeptId(sysUser.getDeptId());
                customer1.setDeptName(sysUser.getDeptName());

                CustomerDongtai customerDongtai = new CustomerDongtai();
                customerDongtai.setCustomerId(customer1.getId());
                customerDongtai.setType(DongTaiTypeEnum.OPERATE.getStatus());
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-自建客户已有客户经理-" + customer1.getUserName());
                customerDongtaiService.save(customerDongtai);
            }
            customer1.setPushId(pushId);
            customer1.setCusName(customer.getCusName());
            customer1.setCityName(customer.getCityName());
            customer1.setLaiyuan(customer.getLaiyuan());
            customer1.setLaiyuanType("2");
            customer1.setAmount(customer.getAmount());
            customer1.setCarNo(customer.getCarNo());
            customer1.setCarStatus(customer.getCarStatus());
            customer1.setFuckCarNoTime(customer.getFuckCarNoTime());
            customer1.setPgPrice(customer.getPgPrice());
            customer1.setRemark(customer.getRemark());

            // 最后进线时间
            customer1.setReceiveTime(new Date());
            // 最后分配时间
            customer1.setLastTime(new Date());
            // 操作时间
            customer1.setOperateTime(new Date());
            customer1.setOwnType("2");
            customer1.setIsRep(isRep);
            customer1.setStatus("0");
            if (StringUtils.isNotNull(customer.getDiyaTime())) {
                customer1.setDiyaTime(customer.getDiyaTime());
            }
            boolean saveSuccess = customerService.save(customer1);
            if (saveSuccess) {
                //保存线索成本记录（自建重复的也需要计算成本）
                XiansuoChengbenLog xiansuoChengbenLogParam = new XiansuoChengbenLog();
                xiansuoChengbenLogParam.setCityName(customer1.getCityName());
                xiansuoChengbenLogParam.setLaiyuan(customer1.getLaiyuan());
                xiansuoChengbenLogParam.setLaiyuanType(customer1.getLaiyuanType());
                xiansuoChengbenLogParam.setCustomerId(customer1.getId());
                xiansuoChengbenLogParam.setIsRep(1);
                xiansuoChengbenLogParam.setIsSum(1);

                CustomerDongtai customerDongtai = new CustomerDongtai();
                customerDongtai.setCustomerId(customer1.getId());
                customerDongtai.setType(DongTaiTypeEnum.OPERATE.getStatus());
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-自建客户信息（重复）-" + customer1.getLaiyuan());
                // 记录我的接单
                CustomerReceive customerReceive = new CustomerReceive();
                customerReceive.setUserId(customer1.getUserId());
                customerReceive.setUserName(customer1.getUserName());
                customerReceive.setDeptId(customer1.getDeptId());
                customerReceive.setDeptName(customer1.getDeptName());
                customerReceive.setCompanyId(customer1.getCompanyId());
                customerReceive.setRemark("自建线索");
                customerReceive.setShareTime(new Date());
                customerReceive.setCustomerId(customer1.getId());
                customerReceive.setLaiyuan(customer1.getLaiyuan());
                customerReceiveService.save(customerReceive);
                customerDongtaiService.save(customerDongtai);
                xiansuoChengbenLogService.saveByCityAndLaiyuan(xiansuoChengbenLogParam);

                // 保存推送记录
                PushCustomer pushCustomer = new PushCustomer();
                pushCustomer.setStatus("2");
                pushCustomer.setId(pushId);
                pushCustomer.setIsNewRecord();
                pushCustomer.setCusName(customer.getCusName());
                pushCustomer.setPhone(customer.getPhone());
                pushCustomer.setIsRep(isRep);
                pushCustomer.setLaiyuan(customer.getLaiyuan());
                pushCustomer.setCityName(customer.getCityName());
                pushCustomer.setRemark("自建客户信息（重复）");
                pushCustomer.setCreateTime(date);
                pushCustomerService.save(pushCustomer);
            }
            return R.status(saveSuccess);
        } else {
            Integer isRep = 0;
            customer.setId(Md5Utils.hash(customer.getPhone()));
            customer.setIsNewRecord();
            // 最后进线时间
            customer.setReceiveTime(new Date());
            // 最后分配时间
            customer.setLastTime(new Date());
            // 操作时间
            customer.setOperateTime(new Date());
            customer.setOwnType("2");
            customer.setLaiyuanType("2");
            customer.setIsRep(0);
            customer.setPushId(pushId);

            if (StringUtils.isEmpty(customer.getStatus())) {
                customer.setStatus("0");
            }
            //保存线索成本记录（自建重复的也需要计算成本）
            XiansuoChengbenLog xiansuoChengbenLogParam = new XiansuoChengbenLog();
            xiansuoChengbenLogParam.setCityName(customer.getCityName());
            xiansuoChengbenLogParam.setLaiyuan(customer.getLaiyuan());
            xiansuoChengbenLogParam.setLaiyuanType(customer.getLaiyuanType());
            xiansuoChengbenLogParam.setCustomerId(customer.getId());
            xiansuoChengbenLogParam.setIsRep(isRep);
            xiansuoChengbenLogParam.setIsSum(1);

            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType(DongTaiTypeEnum.OPERATE.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-自建客户信息-" + customer.getLaiyuan());
            // 记录我的接单
            CustomerReceive customerReceive = new CustomerReceive();
            customerReceive.setUserId(customer.getUserId());
            customerReceive.setUserName(customer.getUserName());
            customerReceive.setDeptId(customer.getDeptId());
            customerReceive.setDeptName(customer.getDeptName());
            customerReceive.setCompanyId(customer.getCompanyId());
            customerReceive.setRemark("自建线索");
            customerReceive.setShareTime(new Date());
            customerReceive.setCustomerId(customer.getId());
            customerReceive.setLaiyuan(customer.getLaiyuan());
            customerReceiveService.save(customerReceive);
            customerDongtaiService.save(customerDongtai);
            xiansuoChengbenLogService.saveByCityAndLaiyuan(xiansuoChengbenLogParam);


            // 保存推送记录
            PushCustomer pushCustomer = new PushCustomer();
            pushCustomer.setStatus("2");
            pushCustomer.setId(pushId);
            pushCustomer.setIsNewRecord();
            pushCustomer.setCusName(customer.getCusName());
            pushCustomer.setPhone(customer.getPhone());
            pushCustomer.setIsRep(isRep);
            pushCustomer.setLaiyuan(customer.getLaiyuan());
            pushCustomer.setCityName(customer.getCityName());
            pushCustomer.setRemark("自建客户信息");
            pushCustomer.setCreateTime(date);
            pushCustomerService.save(pushCustomer);

            return R.status(customerService.save(customer));
        }
    }

    /**
     * 修改左心房客户推送信息
     */
//    @PreAuthorize("@ss.hasPermi('biz:bizCustomer:edit')")
    // @Log(title = "左心房客户推送信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated Customer customer) {
        if (!StringUtils.isNull(customer.getIsDail()) && 1L == customer.getIsDail()) {
            customer.setDailTime(new Date());
        }
        if (null == customer.getLevel()) {
            customer.setLevel(0);
        }
        CustomerDongtai customerDongtai = new CustomerDongtai();
        customerDongtai.setCustomerId(customer.getId());
        customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
        ;
        String cusStatus = "-";
        for (CustomerEnum customerEnum : CustomerEnum.values()) {
            if (customerEnum.getStatus().equals(customer.getStatus())) {
                cusStatus += customerEnum.getStatusValue();
                break;
            }
        }
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-更新客户信息" + cusStatus);
        customerDongtaiService.save(customerDongtai);
        return R.status(customerService.save(customer));
    }

    @PostMapping("/updateHeart")
    public R updateHeart(@RequestBody @Validated Customer customer) {
        CustomerDongtai customerDongtai = new CustomerDongtai();
        customerDongtai.setCustomerId(customer.getId());
        customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
        ;
        String cusStatus = "";
        if (2 == customer.getIsHeart()) {
            customer.setToZhongdianTime(new Date());
            cusStatus = "标记重点客户";
        } else if (1 == customer.getIsHeart()) {
            customer.setToZhongdianTime(null);
            cusStatus = "取消重点客户";
        } else {
            return R.fail("操作失败");
        }
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-" + cusStatus);
        if (customerService.updateIsHeart(customer) > 0) {
            customerDongtaiService.save(customerDongtai);
            return R.success();
        } else {
            return R.fail("操作失败");
        }

    }

    /**
     * 删除左心房客户推送信息
     */
    @Log(title = "客户信息删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.status(customerService.deleteCustomerByIds(ids));
    }

    /**
     * 获取最大编号
     */
    @GetMapping("/findMaxSort")
    public R findMaxSort() {
        return R.data(customerService.findMaxSort(new Customer()));
    }

    /**
     * 导出房客户推送信息列表
     */
    @Log(title = "客户导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(Customer customer) {

        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setCompanyId(null);
        } else {
            customer.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        List<Customer> list = customerService.findList(customer);
        ExcelUtil<Customer> util = new ExcelUtil<Customer>(Customer.class);
        return util.exportExcel(list, "客户信息导出");
    }

    /**
     * 导出房客户推送信息列表
     */
    @Log(title = "客户导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportMd5")
    public R exportMd5(Customer customer) {


        List<CustomerExpertVo> list = customerService.findAllExportList();
        ExcelUtil<CustomerExpertVo> util = new ExcelUtil<CustomerExpertVo>(CustomerExpertVo.class);
        return util.exportExcel(list, "客户加密导出");
    }

    @Log(title = "客户信息导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, String status) throws Exception {
        ExcelUtil<Customer> util = new ExcelUtil<Customer>(Customer.class);
        List<Customer> customerList = util.importExcel(file.getInputStream());
        String message = customerService.importData(customerList, status);
        return AjaxResult.success(message);
    }

    @Log(title = "客户信息修改", businessType = BusinessType.UPDATE)
    @PostMapping("/updateStatus")
    public R updateStatus(@RequestBody Customer customer) throws Exception {


        // 公海领取  //到我的线索池或者到我的客户
        if (CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus()) || CustomerEnum.YI_FP.getStatus().equals(customer.getStatus())) {
            BusinessSet businessSet = businessSetService.get("index_set");
            if (1 == (businessSet.getIsTime())) {
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                Date setTime = sdf.parse(businessSet.getStartTime());
                Date endTime = sdf.parse(businessSet.getEndTime());
                LocalTime now = LocalTime.now();
                // 定义时间段
                LocalTime startTime1 = LocalTime.of(setTime.getHours(), setTime.getMinutes(), setTime.getSeconds());
                // 上午9点
                LocalTime endTime1 = LocalTime.of(endTime.getHours(), endTime.getMinutes(), endTime.getSeconds()); //
                // 下午5点
                if (now.isAfter(startTime1) && now.isBefore(endTime1)) {
                    customer.setUserId(SecurityUtils.getUserId());
                    customer.setUserName(SecurityUtils.getLoginUser().getUser().getName());
                    customer.setDeptId(SecurityUtils.getDeptId());
                    customer.setDeptName(SecurityUtils.getLoginUser().getUser().getDeptName());
                    customer.setToGonghaiTime(null);
                    customer.setToHeimingdanTime(null);
                } else {
                    return R.fail("不在获取公海客户的时间段");
                }
            }
        }

        // 操作时间
        customer.setOperateTime(new Date());

        CustomerDongtai customerDongtai = null;
        for (String id : customer.getIds()) {
            customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(id);
            customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
            ;
            if (customer.getStatus().equals(CustomerEnum.GONG_HAI.getStatus())) {
                customer.setToGonghaiTime(new Date());
                customer.setIsLock(0);
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-更新信息-(转入公海)");
            }
            if (customer.getStatus().equals(CustomerEnum.HEI_MINGDAN.getStatus())) {
                customer.setToHeimingdanTime(new Date());
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-更新信息-(转入黑名单)");
            }
            if (customer.getStatus().equals(CustomerEnum.YI_FP.getStatus())) {
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-更新信息-(转入线索池)");
            }
            if (customer.getStatus().equals(CustomerEnum.MY_CUS.getStatus())) {
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-更新信息-(转入我的客户)");
            }
            customerDongtaiService.save(customerDongtai);
            if (customer.getStatus().equals(CustomerEnum.GONG_HAI.getStatus()) || customer.getStatus().equals(CustomerEnum.HEI_MINGDAN.getStatus())) {
                CustomerXiezu customerXiezu = new CustomerXiezu();
                customerXiezu.setCustomerId(id);
                customerXiezuService.deleteByCustomerId(customerXiezu);
                customerDongtai = new CustomerDongtai();
                customerDongtai.setCustomerId(id);
                customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
                ;
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-客户到公海-(删除协助人员)");
                customerDongtaiService.save(customerDongtai);
            }
        }

        if (CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus()) || CustomerEnum.YI_FP.getStatus().equals(customer.getStatus())) {
            return customerService.updateMyStatus(customer) > 0 ? R.success() : R.fail("操作错误");
        } else {
            return customerService.updateStatus(customer) > 0 ? R.success() : R.fail("操作错误");
        }
    }

    @Log(title = "公海领取客户", businessType = BusinessType.UPDATE)
    @PostMapping("/updateStatusGongHai")
    public R updateStatusGongHai(@RequestBody Customer customer) throws Exception {
        // 公海领取  //到我的线索池或者到我的客户
        if (CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus()) || CustomerEnum.YI_FP.getStatus().equals(customer.getStatus())) {
            BusinessSet businessSet = businessSetService.get("index_set");
            if (1 == (businessSet.getIsTime())) {
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                Date setTime = sdf.parse(businessSet.getStartTime());
                Date endTime = sdf.parse(businessSet.getEndTime());
                LocalTime now = LocalTime.now();
                // 定义时间段
                LocalTime startTime1 = LocalTime.of(setTime.getHours(), setTime.getMinutes(), setTime.getSeconds());
                // 上午9点
                LocalTime endTime1 = LocalTime.of(endTime.getHours(), endTime.getMinutes(), endTime.getSeconds()); //
                // 下午5点
                if (now.isAfter(startTime1) && now.isBefore(endTime1)) {
                    customer.setUserId(SecurityUtils.getUserId());
                    customer.setUserName(SecurityUtils.getLoginUser().getUser().getName());
                    customer.setDeptId(SecurityUtils.getDeptId());
                    customer.setDeptName(SecurityUtils.getLoginUser().getUser().getDeptName());
                } else {
                    return R.fail("不在获取公海客户的时间段");
                }
            }
        }
        CustomerDongtai customerDongtai = null;
        for (String id : customer.getIds()) {
            customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(id);
            customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
            ;
            if (customer.getStatus().equals(CustomerEnum.YI_FP.getStatus())) {
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-更新信息-(转入线索池)");
            }
            if (customer.getStatus().equals(CustomerEnum.MY_CUS.getStatus())) {
                customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-更新信息-(转入我的客户)");
            }
            customerDongtaiService.save(customerDongtai);
        }

        if (CustomerEnum.MY_CUS.getStatus().equals(customer.getStatus()) || CustomerEnum.YI_FP.getStatus().equals(customer.getStatus())) {
            return customerService.updateMyStatus(customer) > 0 ? R.success() : R.fail("操作错误");
        } else {
            return customerService.updateStatus(customer) > 0 ? R.success() : R.fail("操作错误");
        }
    }

    /**
     * 首页查询用户信息
     *
     * @param customer
     * @return
     */
    @Log(title = "首页查询用户信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/findCustomerByPhone")
    public R findCustomerByPhone(Customer customer) {
        Customer customerOne = customerService.findByPhone(customer);
        return R.data(customerOne);
    }

    /**
     * 首页查询用户信息
     *
     * @param customer
     * @return
     */
    @Log(title = "首页查询用户信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/findCustomerByNameOrPhone")
    public R findCustomerByNameOrPhone(Customer customer) {
        List<Customer> customerList = customerService.findByNameOrPhone(customer);
        return R.data(customerList);
    }

    /**
     * 锁定客户
     *
     * @param customer
     * @return
     */
    @Log(title = "锁定/取消锁客 客户", businessType = BusinessType.SELECT)
    @GetMapping(value = "/lockCustomer")
    public R lockCustomer(Customer customer) {
        CustomerDongtai customerDongtai = new CustomerDongtai();
        if (null != customer.getIsLock() && customer.getIsLock() == 1) {
            Integer lockCounts = customerService.findLocks(customer);
            BusinessSet businessSet = businessSetService.get("index_set");
            if (lockCounts >= businessSet.getManagerLockNums()) {
                return R.fail("锁定客户数量已经到上线：" + businessSet.getManagerLockNums());
            }
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
            ;
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-锁定客户");
            customerDongtaiService.save(customerDongtai);
        } else {
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
            ;
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-解锁客户");
            customerDongtaiService.save(customerDongtai);
        }
        return R.status(customerService.lockCustomer(customer));
    }


    /**
     * 工资统计
     *
     * @param customer
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/yuangonggongzitongji")
    public R yuangonggongzitongji(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        if (!StringUtils.isNotNull(customer.getCreateTime())) {
            customer.setCreateTime(new Date());
        }
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.yuangonggongzitongji(customer));
    }

    /**
     * 工资统计导出
     *
     * @param customer
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/exportyuangonggongzitongji")
    public R exportyuangonggongzitongji(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        List<YuanGongGongziVo> list = customerService.yuangonggongzitongji(customer);
        ExcelUtil<YuanGongGongziVo> util = new ExcelUtil<YuanGongGongziVo>(YuanGongGongziVo.class);
        return util.exportExcel(list, "员工工资统计");
    }

    /**
     * 查看客户电话
     *
     * @param customer
     * @return
     */
    @GetMapping("/lookPhone")
    public R lookPhone(Customer customer) {
        CustomerDongtai customerDongtai = new CustomerDongtai();
        customerDongtai.setCustomerId(customer.getId());
        customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
        ;
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-后台查看客户电话");
        return R.status(customerDongtaiService.save(customerDongtai));
    }

    /**
     * 查看客户电话
     *
     * @param customer
     * @return
     */
    @GetMapping("/lookAppPhone")
    public R lookAppPhone(Customer customer) {
        CustomerDongtai customerDongtai = new CustomerDongtai();
        customerDongtai.setCustomerId(customer.getId());
        customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
        ;
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-APP查看客户电话");
        return R.status(customerDongtaiService.save(customerDongtai));
    }

    /**
     * testWebSocket
     *
     * @return
     */
    @GetMapping("/testWebSocket")
    public R testWebSocket() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "fenpeiNewCus");
        jsonObject.put("msg", SecurityUtils.getLoginUser().getUser().getName() + "-分配新客户给您了");
        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_APP, SecurityUtils.getUserId(),
                jsonObject.toJSONString());
        return R.success();
    }

    /**
     * testWebSocket
     *
     * @return
     */
    @GetMapping("/testWebSocketPc")
    public R testWebSocketByPc() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "fenpeiNewCus");
        jsonObject.put("msg", SecurityUtils.getLoginUser().getUser().getName() + "-分配新客户给您了");
        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, SecurityUtils.getUserId(),
                jsonObject.toJSONString());
        return R.success();
    }

    @GetMapping("/testWebSocketPc2")
    public R testWebSocketByPc2() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "xiezuCus");
        jsonObject.put("msg", SecurityUtils.getLoginUser().getUser().getName() + "-分配新客户给您了");
        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, SecurityUtils.getUserId(),
                jsonObject.toJSONString());
        return R.success();
    }

    /**
     * testWebSocket
     *
     * @return
     */
    @GetMapping("/playCall")
    public R playCall(Customer customer) {
        // 查询用户是否在线
        Session session =
                WebSocketUsers.getUsers().get(WebSocketUsers.TYPE_APP + SecurityUtils.getLoginUser().getUser().getId());
        // 判断是否在线
        if (null != session) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "playCall");
            jsonObject.put("phone", customer.getPhone());
            jsonObject.put("customerId", customer.getId());
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_APP,
                    SecurityUtils.getLoginUser().getUser().getId(), jsonObject.toJSONString());
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(customer.getId());
            customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
            ;
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-后台拨打电话");
            customerDongtaiService.save(customerDongtai);
            return R.success("启动成功，请查看手机！");
        } else {
            return R.fail("设备不在线！");
        }

    }

    /**
     * 回传评分推送信息
     */
    @Log(title = "回传评分推送信息", businessType = BusinessType.UPDATE)
    @PostMapping("/clueRate")
    public R clueRate(@RequestBody Customer customer) {
        //  来源为广告线索
        if (StringUtils.isNotNull(customer.getZkStatus()) && StringUtils.isNotNull(customer.getIsRep()) && StringUtils.isNotNull(customer.getLaiyuanType())) {
            if (null != customer.getLevel() && !"1".equals(customer.getZkStatus()) && 1 != customer.getIsRep() && "1".equals(customer.getLaiyuanType())) {
                if ("乐数云".equals(customer.getLaiyuan())) {
                    // 回传
                    String return_url = "https://crm.lejiangtang.com/ljt/web/api/ljt/api/callbackClue";
                    JSONObject params = new JSONObject();
                    params.put("clueId", customer.getClueId());
                    String dataType = "";
                    if (0 == (customer.getLevel())) {
                        dataType = "ONE_STAR";
                    } else if (1 == (customer.getLevel())) {
                        dataType = "ONE_STAR";
                    } else if (2 == (customer.getLevel())) {
                        dataType = "TWO_STAR";
                    } else if (3 == (customer.getLevel())) {
                        dataType = "THREE_STAR";
                    } else if (4 == (customer.getLevel())) {
                        dataType = "FOUR_STAR";
                    } else if (5 == (customer.getLevel())) {
                        dataType = "FIVE_STAR";
                    }
                    params.put("dataType", dataType);
                    JSONObject result = JSONObject.parseObject(HttpUtils.doPost(return_url, params));
                    if (StringUtils.isNotNull(result)) {
                        CustomerDongtai customerDongtai = new CustomerDongtai();
                        customerDongtai.setCustomerId(customer.getId());
                        customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
                        ;
                        customerDongtai.setContent(customer.getLaiyuan() + "-回传客户评级-" + (result.getString("code").equals("200") ? "成功" : "失败"));
                        customerDongtaiService.save(customerDongtai);
                    }
                }
                if ("融享客".equals(customer.getLaiyuan())) {
                    // 回传
                    String return_url = RongXiangKeAESUtil.HOST + "/crm-report/api/clue/gradeSync";
                    JSONObject params = new JSONObject();
                    params.put("requestId", UUID.randomUUID());
                    params.put("voucherCode", RongXiangKeAESUtil.VOUCHER_CODE);
                    JSONObject data = new JSONObject();
                    data.put("orderNo", customer.getClueId());
                    int grade = 0;
                    if (0 == (customer.getLevel())) {
                        grade = 0;
                    } else if (1 == (customer.getLevel())) {
                        grade = 10;
                    } else if (2 == (customer.getLevel())) {
                        grade = 20;
                    } else if (3 == (customer.getLevel())) {
                        grade = 30;
                    } else if (4 == (customer.getLevel())) {
                        grade = 40;
                    } else if (5 == (customer.getLevel())) {
                        grade = 50;
                    }
                    data.put("grade", grade);
                    params.put("data", RongXiangKeAESUtil.encrypt(data.toJSONString(), RongXiangKeAESUtil.KEY));
                    JSONObject result = JSONObject.parseObject(HttpUtils.doPost(return_url, params));
                    if (StringUtils.isNotNull(result)) {
                        CustomerDongtai customerDongtai = new CustomerDongtai();
                        customerDongtai.setCustomerId(customer.getId());
                        customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
                        ;
                        customerDongtai.setContent(customer.getLaiyuan() + "-回传客户评级-" + (result.getString("msg").equals("success") ? "成功" : "失败"));
                        customerDongtaiService.save(customerDongtai);
                    }
                }
                if ("融薪花".equals(customer.getLaiyuan())) {
                    // 回传
                    String return_url = RongXiangKeAESUtil.HOST + "/crm-report/api/clue/gradeSync";
                    JSONObject params = new JSONObject();
                    params.put("requestId", UUID.randomUUID());
                    params.put("voucherCode", customer.getClueId());
                    JSONObject data = new JSONObject();
                    data.put("orderNo", customer.getClueId());
                    data.put("grade", customer.getLevel());
                    params.put("data", RongXiangKeAESUtil.encrypt(data.toJSONString(), RongXiangKeAESUtil.KEY));
                    JSONObject result = JSONObject.parseObject(HttpUtils.doPost(return_url, params));
                    if (StringUtils.isNotNull(result)) {
                        CustomerDongtai customerDongtai = new CustomerDongtai();
                        customerDongtai.setCustomerId(customer.getId());
                        customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
                        ;
                        customerDongtai.setContent(customer.getLaiyuan() + "-回传客户评级-" + (result.getString("msg").equals("success") ? "成功" : "失败"));
                        customerDongtaiService.save(customerDongtai);
                    }
                }

                if ("云象优客".equals(customer.getLaiyuan())) {
                    String return_url = "";
                    if (StringUtils.isNotEmpty(return_url)) {
                        JSONObject params = new JSONObject();
                        Long timestamp = System.currentTimeMillis();
                        params.put("consumeTime", timestamp);
                        params.put("orgOpenId", customer.getApiSourceName());
                        JSONObject data = new JSONObject();
                        data.put("orderBizNo", customer.getClueId());
                        data.put("star", StringUtils.isNotNull(customer.getLevel()) ? "0" : customer.getLevel());
                        String dataAes = YunXiangYouKeAESUtils.encrypt(YunXiangYouKeAESUtils.KEY,
                                YunXiangYouKeAESUtils.IV, data.toJSONString());
                        params.put("data", dataAes);
                        params.put("sign",
                                Md5Utils.hash(YunXiangYouKeAESUtils.APPID + YunXiangYouKeAESUtils.APPKEY + dataAes));
                        JSONObject result = JSONObject.parseObject(HttpUtils.doPost(return_url, params));
                        if (StringUtils.isNotNull(result)) {
                            CustomerDongtai customerDongtai = new CustomerDongtai();
                            customerDongtai.setCustomerId(customer.getId());
                            customerDongtai.setType(DongTaiTypeEnum.SYSTEM.getStatus());
                            ;
                            customerDongtai.setContent(customer.getLaiyuan() + "-回传客户评级-" + (result.getString("msg").equals("success") ? "成功" : "失败"));
                            customerDongtaiService.save(customerDongtai);
                        }
                    }
                }
            }
        }
        return R.status(customerService.save(customer));
    }


    /**
     * 查询我的接单列表，包含客户信息
     */
    //@PreAuthorize("@ss.hasPermi('biz:bizCustomerReceive:list')")
    @GetMapping("/findMyReceiveList")
    public R<PageInfo> findMyReceiveList(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setReceive_userId(null);
        } else {
            // 只查询自己的接单
            customer.setReceive_userId(SecurityUtils.getLoginUser().getUserId());
        }
        customer.setPage(new PageDomain(request, response));
        return R.data(customerService.findMyReceiveList(customer));
    }


    @GetMapping("/findWillToGongHaiList")
    public R<PageInfo> findWillToGongHaiList(Customer customer, HttpServletRequest request,
            HttpServletResponse response) {

        customer.setPage(new PageDomain(request, response));

        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setUserId(SecurityUtils.getUserId());
        }

        return R.data(customerService.findWillToGongHaiList(customer));
    }


    @GetMapping("/findWeiJieWillToShareList")
    public R<PageInfo> findWeiJieWillToShareList(Customer customer, HttpServletRequest request,
            HttpServletResponse response) {

        customer.setPage(new PageDomain(request, response));

        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            customer.setUserId(SecurityUtils.getUserId());
        }

        return R.data(customerService.findWeiJieWillToShareList(customer));
    }


    @GetMapping("/getAudioToText")
    public R getAudioToText(CustomerFile customerFile, HttpServletRequest request, HttpServletResponse response) throws NoApiKeyException, InputRequiredException, UploadFileException {
        if (StringUtils.isNotNull(customerFile.getUrl())) {
            GenerationResult result = AliQwenUtils.callWithMessage(customerFile.getUrl());
            List<String> content =
                    Arrays.stream(result.getOutput().getChoices().get(0).getMessage().getContent().replace("*", "").split("\n")).collect(Collectors.toList());
            return R.data(content);
        } else {
            return R.fail("请上传音频文件");
        }

    }

}
